package com.lablzh.gdxy.controller;

import com.lablzh.gdxy.component.UserDetailsUtil;
import com.lablzh.gdxy.entity.Teacher;
import com.lablzh.gdxy.entity.activity.*;
import com.lablzh.gdxy.entity.course.Course;
import com.lablzh.gdxy.entity.practice.Practice;
import com.lablzh.gdxy.repository.activity.ProjectRepository;
import com.lablzh.gdxy.repository.activity.StudentTeamRepository;
import com.lablzh.gdxy.repository.activity.TeamProjectRepository;
import com.lablzh.gdxy.repository.activity.TeamRepository;
import com.lablzh.gdxy.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.redis.core.ReactiveHashOperationsExtensionsKt;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import sun.nio.cs.ext.IBM037;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/activity")
public class ActivityController {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private TeamRepository teamRepository;
    @Autowired
    private UserDetailsUtil userDetailsUtil;
    @Autowired
    private StudentTeamRepository studentTeamRepository;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private TeamProjectRepository teamProjectRepository;

    /**
     * 增加创新活动参数
     * @param activityPram
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @PostMapping("/activityPram")
    public String addActivityPram(@RequestBody ActivityPram activityPram) {
        return activityService.addActivityPram(activityPram);
    }

    /**
     * 编辑创新活动参数
     *
     * @param activityPram
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @PutMapping("/activityPram")
    public String updateActivityPram(@RequestBody ActivityPram activityPram) {
        return activityService.updateActivityPram(activityPram);
    }

    /**
     * 通过名称获取
     *
     * @param activityName
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @GetMapping("/oneActivityPram")
    public ActivityPram getOneActivityPram(@RequestParam("activityName") String activityName) {
        return activityService.getOneActivityPram(activityName);
    }

    /**
     * 获取所有参数
     *
     * @return
     */
    @PreAuthorize("hasAnyRole('admin','teacher','student')")
    @GetMapping("/activityPram")
    public List<ActivityPram> getActivityPram() {
        return activityService.getActivityPram();
    }

    /**
     * 删除创新活动参数
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @DeleteMapping("/activitiPram")
    public String deleteActivityPram(@RequestParam("ID") Integer id) {
        return activityService.deleteActivityPram(id);
    }

    /**
     * 添加课外科技活动
     *
     * @param project
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin','student')")
    @PostMapping("/project")
    public String addProject(@RequestBody Project project) {
        return activityService.addProject(project);
    }

    /**
     * 更新课外科技活动
     *
     * @param project
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/project")
    public String updateProject(@RequestBody Project project) {
        return activityService.updateProject(project);
    }

    /**
     * 根据id获取课外科技活动
     * @param id
     * @return
     */
    @GetMapping("/oneProject")
    public Project getOneProject(@RequestParam("ID") Integer id) {
        return activityService.getOneProject(id);
    }

    /**
     * 获取所有课外科技活动
     *
     * @return
     */
    @GetMapping("/project")
    public List<Project> getProject() {
        return activityService.getProject();
    }

    /**
     * 课外科技活动多条件查询 projectName category audit
     *
     * @param project
     * @param page
     * @return
     */
    @PreAuthorize("hasAnyRole('admin', 'teacher','student')")
    @PostMapping("/queryActivity")
    public Map getQueryAllActivity(@RequestBody(required = false) Project project,
                                   @RequestParam(name = "page", defaultValue = "0") Integer page) {
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("projectName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("category", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("audit", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<Project> example = Example.of(project, exampleMatcher);
        Pageable designPage = PageRequest.of(page - 1, 20, Sort.by(Sort.Direction.DESC, "id"));
        Page<Project> all = projectRepository.findAll(example, designPage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("project", all.getContent());
        return data;
    }


    /**
     * 根据id获取课外科技活动
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @DeleteMapping("/project")
    public String deleteProject(@RequestParam("ID") Integer id) {
        return activityService.deleteProject(id);
    }

    /**
     * 获取某个老师的课外科技活动
     *
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("/projectTeacher")
    public List<Project> getProjectTeacher() {
        return activityService.getProjectTeacher();
    }

    /**
     * 修改课外科技活动审核情况
     *
     * @param id
     * @param audit
     * @return
     */
//    @PreAuthorize("hasAnyRole('teacher')")
    @PutMapping("/projectAudit")
    public String updateProjectAudit(@RequestParam("ID") Integer id, @RequestParam("audit") String audit) {
        return activityService.updateProjectAudit(id, audit);
    }

    /**
     * 根据审核情况获取课外科技活动
     *
     * @param audit
     * @return
     */

    @GetMapping("/projectByAudit")
    public List<Project> getProjectByAudit(@RequestParam("audit") String audit) {
        return activityService.getProjectByAudit(audit);
    }

    /**
     * 添加团队
     *
     * @param team
     * @return
     */
    // @PreAuthorize("hasAnyRole('student')")
    @PostMapping("/team")
    public String addTeam(@RequestBody Team team) {
        return activityService.addTeam(team);
    }

    /**
     * 修改团队
     *
     * @param team
     * @return
     */
    // @PreAuthorize("hasAnyRole('student')")
    @PutMapping("/team")
    public String updateTeam(@RequestBody Team team) {
        return activityService.updateTeam(team);
    }

    /**
     * 根据id获取团队
     *
     * @param id
     * @return
     */
    // @PreAuthorize("hasAnyRole('student', 'teacher')")
    @GetMapping("/oneTeam")
    public Team getOneTeam(@RequestParam("ID") Integer id) {
        return activityService.getOneTeam(id);
    }

//    private String teamName;//团队名称
//    private String introduction;//团队描述
//    private String captainUsername;//队长学号
//    private String captain;//队长

    /**
     * 多条件查询队伍
     * //    private String teamName;//团队名称
     * //    private String introduction;//团队描述
     * //    private String captainUsername;//队长学号
     * //    private String captain;//队长
     * @param team
     * @param page
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin', 'student')")
    @PostMapping("/queryTeam")
    public Map getQueryAllTeam(@RequestBody(required = false) Team team, @RequestParam(name = "page", defaultValue = "0") Integer page) {
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("teamName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("introduction", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("captainUsername", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("captain", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<Team> example = Example.of(team, exampleMatcher);
        Pageable designPage = PageRequest.of(page - 1, 20, Sort.by(Sort.Direction.DESC, "id"));
        Page<Team> all = teamRepository.findAll(example, designPage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("team", all.getContent());
        return data;
    }

    /**
     * 获取所有团队
     * @return
     */
    @GetMapping("/team")
    public List<Team> getTeam() {
        return activityService.getTeam();
    }

    /**
     * 根据id删除团队
     * 根据id
     *
     * @param id
     * @return
     */
    @DeleteMapping("/team")
    public String deleteTeam(@RequestParam("ID") Integer id) {
        String captainUsername = teamRepository.findById(id).orElse(null).getCaptainUsername();
        if (userDetailsUtil.getUserDetails().equals(captainUsername) || userDetailsUtil.getUserRole().equals("ROLE_admin")) {
            return activityService.deleteTeam(id);
        } else {
            return "你无权删除！";
        }
    }

    /**
     * 获取我创建的团队
     */
    @GetMapping("/teamLeader")
    public List<Team> getTeamLeader() {
        return activityService.getTeamLeader();
    }

    /**
     * 获取我参与的团队
     *
     * @return
     */
    @GetMapping("/teamJoin")
    public List<Team> getTeamJoin() {
        return activityService.getTeamJoin();
    }

    /**
     * 申请团队
     *
     * @param teamName
     * @return
     */
    @PostMapping("/studentTeam")
    public String addStudentTeam(@RequestParam("TeamName") String teamName, @RequestParam("introduction") String introduction) {
        return activityService.addStudentTeam(teamName, introduction);
    }
    @PostMapping("/teamJoinProject")
    public List<TeamProject> teamJoinProject(@RequestParam("TeamName") String teamName) {
        return teamProjectRepository.findAllByTeamName(teamName);
    }
    @PostMapping("/deleteTeamJoinProject")
    public String deleteTeamJoinProject(@RequestParam("id") Integer id) {
        TeamProject teamProject = teamProjectRepository.findById(id).orElse(null);
        if("已通过".equals(teamProject.getAudit()))
        {
            return "已通过申请不可撤回";
        }
        Team byTeamName = teamRepository.findByTeamName(teamProject.getTeamName());
        String userDetails = userDetailsUtil.getUserDetails();
        if(userDetails.equals(byTeamName.getCaptainUsername()))
        {
            teamProjectRepository.deleteById(id);
            return "删除成功";
        }

        return "您不是队长，不可操作";
    }

    /**
     * 根据学生团队ID删除学生团队
     *
     * @param id
     * @return
     */
    @DeleteMapping("/studentTeam")
    public String deleteStudentTeam(@RequestParam("ID") Integer id) {
        StudentTeam studentTeam = studentTeamRepository.findById(id).orElse(null);
        String captainUsername = teamRepository.findByTeamName(studentTeam.getTeamName()).getCaptainUsername();
        if (userDetailsUtil.getUserDetails().equals(captainUsername)) {
            return activityService.deleteStudentTeam(id);
        } else {
            return "你不是队长，不能删除";
        }

    }

    @DeleteMapping("/studentTeamByTeam")
    public String deleteStudentTeamByTeamName(@RequestParam("teamName") String teamName) {
        return activityService.deleteStudentTeamByTeamName(teamName);
    }

    /**
     * 根据团队名获取学生团队表
     *
     * @param teamName
     * @return
     */
    @GetMapping("/studentTeamByTeam")
    public List<StudentTeam> getStudentTeamByTeam(@RequestParam("TeamName") String teamName) {
        return activityService.getStudentTeamByTeam(teamName);
    }

    /**
     * 修改学生团队表申请情况
     *
     * @param id
     * @param audit
     * @return
     */
    @PutMapping("/studentTeamAudit")
    public String updateStudentTeamAudit(@RequestParam("ID") Integer id, @RequestParam("audit") String audit) {
        return activityService.updateStudentTeamAudit(id, audit);
    }

    /**
     * 添加团队项目表
     *
     * @param teamName
     * @param projectName
     * @return
     */
    @PostMapping("/teamProject")
    public String addTeamProject(@RequestParam("teamName") String teamName,
                                 @RequestParam("projectName") String projectName) {
        return activityService.addTeamProject(teamName, projectName);
    }


    /**
     * 修改团队项目表审核情况
     *
     * @param id
     * @param audit
     * @return
     */
    @PutMapping("/teamProjectAudit")
    public String updateTeamProjectAudit(@RequestParam("ID") Integer id, @RequestParam("audit") String audit) {
        return activityService.updateTeamProjectAudit(id, audit);
    }

    @GetMapping("/teamProject")
    public List<TeamProject> getTeamProject(@RequestParam("projectName") String projectName) {
        return activityService.getTeamProject(projectName);
    }


    /**
     * 添加blog
     * @param blog
     * @return
     */
    @PostMapping("/blog")
    public String addBlog(@RequestBody Blog blog) {
        return activityService.addBlog(blog);
    }


    @GetMapping("/blog")
    public List<Blog> getAllBlog() {
        return activityService.getAllBlog();
    }

    /**
     * 根据id获取blog
     * @param id
     * @return
     */
    @GetMapping("/oneBlog")
    public Blog getOneBlog(@RequestParam("ID") Integer id) {
        return activityService.getOneBlog(id);
    }

    /**
     * 根据项目获取blog
     * @param projectName
     * @return
     */
    @GetMapping("/blogByPorject")
    public List<Blog> getBlogByPorjectName(@RequestParam("projectName") String projectName) {
        return activityService.getBlogByPorjectName(projectName);
    }

    /**
     * 根据主题获取blog
     *
     * @param theme
     * @return
     */
    @GetMapping("/blogByTheme")
    public List<Blog> getBlogByTheme(@RequestParam("theme") String theme) {
        return activityService.getBlogByTheme(theme);
    }
    @DeleteMapping("/deleteBlog")
    public String deleteBlog(@RequestParam("id") int id) {
        return activityService.deleteBlog(id);

    }

}
